package com.wt.springboot.demo.custom.resolverhandler;

import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;

/**
 * @author wangtao
 * @date 2023/3/5 19:03
 **/
public class MyCustomReturnValueHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        //判断方法是否包含自定义注解MyResonse或者返回结果是指定的某种类型
        return returnType.getMethodAnnotation(MyResponse.class) != null || ResponseResult.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        // 表明该请求已经处理，后面spring不会再处理
        mavContainer.setRequestHandled(true);
        if (returnValue != null && ResponseResult.class.isAssignableFrom(returnType.getParameterType())) {
            String msg = ((ResponseResult<?>)returnValue).getCode() == 0 ? "成功" : "失败";
            ((ResponseResult<?>)returnValue).setMsg(msg);
        }
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        System.out.println("return value handled by MyCustomReturnValueHandler.");
        response.getWriter().println(JSON.toJSONString(returnValue));
    }
}